package cn.storm.codehelper

import cn.hutool.core.util.StrUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.EditorModificationUtil

class GenTryAction : AnAction() {
    override fun actionPerformed(e: AnActionEvent) {
        println(StrUtil.isNotBlank(""))
        val craet = e.getData(LangDataKeys.CARET)
        //获取选中的内容
        val text = craet!!.editor.selectionModel.selectedText
        //拼接try之后的内容
        val result = generNewTryText(text)
        ApplicationManager.getApplication().runWriteAction{
            WriteCommandAction.runWriteCommandAction(e.project){
                WriteAction.run<RuntimeException> {
                    val start = craet.selectionStart
                    val end = start + result.length
                    EditorModificationUtil.insertStringAtCaret(craet.editor, result)
                    craet.setSelection(start, end)
                }
            }
        }
    }

    private fun generNewTryText(text: String?): String {
        return """try{
                $text
            }catch(Exception e){
                log.error(e.getMessage(), e);
            }""".trimIndent()
    }



}